package top.malaoshi.netdisk.init;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import top.malaoshi.netdisk.Constant;
import top.malaoshi.netdisk.component.NetdisConfigReader;
import top.malaoshi.sprout.jdbc.DbTemplate;
import top.malaoshi.util.Out;
import top.malaoshi.util.io.TextFileReader;
import top.malaoshi.web.utils.PathUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Iterator;

@Component
@Order(400)
public class Init implements CommandLineRunner {
    @Resource
    DbTemplate dbUtils;
    @Resource
    private NetdisConfigReader reader;
    @Override
    public void run() throws Exception {

        String dbPath = reader.getDbPath();

        File dbFile = new File(dbPath, Constant.DB_FILE_NAME);
        System.out.println("数据库路径："+dbFile.getAbsolutePath());
        System.out.println("数据库是否存在："+dbFile.exists());
        if(!dbFile.exists()){
//            DbUtils dbUtils = dbPool.getDbUtils();

            dbUtils.setAutoCommit(false);
            try {
                create();
                insert();
            }catch (Exception e){
                throw  e;
            }finally {

                dbUtils.close();
            }
        }

        // 打开浏览器
//        String url = "http://localhost:"+Constant.port;
//        Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
    }

    public void create() throws SQLException, IOException {
        String classpath = PathUtils.getClassPath().getAbsolutePath();
        File pathAll = new File(classpath , "/create.sql");
        TextFileReader tfr = new TextFileReader(pathAll);
        Iterator<String> iterator = tfr.iterator();
        while(iterator.hasNext()){
            String line = iterator.next();
            if(!"".equals(line)){
                try {
                    dbUtils.update(line);
                    Out.print("执行SQL成功：", line);
                }catch (SQLException e){
                    Out.print("执行SQL报错：", line);
                    throw e;
                }

            }
        }
        dbUtils.commmit();
        tfr.close();

    }

    public void insert() throws SQLException, IOException {
        String classpath = PathUtils.getClassPath().getAbsolutePath();
        File pathAll = new File(classpath , "/insert.sql");
        TextFileReader tfr = new TextFileReader(pathAll,"utf-8");
        Iterator<String> iterator = tfr.iterator();
        while(iterator.hasNext()){
            String line = iterator.next();
            if(!"".equals(line)){
                int n = dbUtils.update(line);
                if(n>0) {
                    Out.print("执行SQL成功：", line);
                }else{

                    Out.print("执行SQL失败：", line);
                }
            }
        }
        dbUtils.commmit();
        tfr.close();

    }
}
